import redis from 'redis'
import config from './index'
const options = {
  ...config.REDIS,
  detect_buffers: true,
  retry_strategy: function (options) {
    if (options.error && options.error.code === 'ECONNREFUSED') {
      // End reconnecting on a specific error and flush all commands with
      // a individual error
      return new Error('The server refused the connection')
    }
    if (options.total_retry_time > 1000 * 60 * 60) {
      // End reconnecting after a specific timeout and flush all commands
      // with a individual error
      return new Error('Retry time exhausted')
    }
    if (options.attempt > 10) {
      // End reconnecting with built in error
      return undefined
    }
    // reconnect after
    return Math.min(options.attempt * 100, 3000)
  },
}

const client = redis.createClient(options)
const { promisify } = require('util')
const getAsync = promisify(client.get).bind(client)

const setValue = (key, val, time) => {
  if (typeof val === 'undefined' || val === null || val === '') {
    return
  }
  if (typeof val === 'string') {
    if (typeof time !== 'undefined') {
      client.set(key, val, 'EX', time)
    } else {
      client.set(key, val)
    }
  } else if (typeof val === 'object') {
    //{key1:val1,key2:val2}
    Object.keys(val).forEach((item) => {
      client.hset(key, item, val[item], redis.print)
    })
  }
}

const getValue = (key) => {
  return getAsync(key)
}

const getHValue = (key) => {
  return promisify(client.hgetall).bind(client)(key)
}

const delValue = (key) => {
  return client.del(key)
}

export { client, getValue, setValue, getHValue, delValue }
